﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Douban.Api.Mail;

namespace Douban.Api.Infrastructure
{
    public class DataSourcePool : IDataSourcePool
    {
        private readonly DoubanContext _context;
        private static IDictionary<Type, Type> _dataSourceRegistry;

        static DataSourcePool()
        {
            _dataSourceRegistry = new Dictionary<Type, Type>
            {
                { typeof(Mailbox), typeof(InboxDataSource) }
            };
        }

        public DataSourcePool(DoubanContext context)
        {
            _context = context;
        }

        public T GetDataSource<T>(string sourceId) where T : IDataSource
        {
            T dataSource = Activator.CreateInstance<T>();
            dataSource.Id = sourceId;

            return dataSource;
        }

        public IDataSource GetDataSource(string sourceId, Type originType)
        {
            Type value = null;

            if (_dataSourceRegistry.TryGetValue(originType, out value))
            {
                IDataSource dataSource = (IDataSource) Activator.CreateInstance(value);
                dataSource.Id = sourceId;

                return dataSource;
            }

            throw new UnknownDataSourceException(originType.FullName);
        }
    }
}
